package top.lshaci.learning.netty.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * GroupChatClient
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
@AllArgsConstructor
public class GroupChatClient {

    private final String host;
    private final int port;

    public static void main(String[] args) throws Exception {
        GroupChatClient client = new GroupChatClient("localhost", 9000);
        client.run();
    }

    public void run() throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientHandler())
            ;
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();

            Channel channel = channelFuture.channel();
            log.debug("{} 启动", channel.localAddress());
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
